import { uuid } from '@/utils/utils';
import {
  DatePickerFormats,
  DatePickerFormatsSelectSetting,
  DEFAULT_CACHE_EXPIRED,
  FilterTypes,
  FilterTypesOperatorSetting,
  IS_RANGE_TYPE,
} from './constants';
import { IControlRelatedField, IFormedView, IGlobalControl, InteractionType, IViewModelProps } from './types';
import OperatorTypes from '@/utils/operatorTypes';
import { ViewModelTypes } from '@/pages/Analysis/Datasheet/components/StructureTabel/constants';
import { ISheetItem } from '@/pages/Analysis/type';

/**
 * 获取默认的全局筛选对象
 */
export function getDefaultGlobalControl(): IGlobalControl {
  const control: IGlobalControl = {
    key: uuid(8, 16),
    name: '新建控制器',
    type: FilterTypes.Select,
    interactionType: 'column',
    operator: FilterTypesOperatorSetting[FilterTypes.InputText][0],
    cache: false,
    expired: DEFAULT_CACHE_EXPIRED,
    width: 0,
    relatedItems: {},
    relatedViews: {},
  };
  return control;
}

export function getDatePickerFormatOptions(type: string | undefined, multiple: undefined | boolean): DatePickerFormats[] {
  switch (type) {
    case FilterTypes.DateRange:
      return multiple
        ? DatePickerFormatsSelectSetting.multiple
        : DatePickerFormatsSelectSetting.normal;
    default:
      return [];
  }
}


export function getOperatorOptions(type: string | undefined, multiple: undefined | boolean): OperatorTypes[] {
  // @ts-ignore
  const operatorTypes = FilterTypesOperatorSetting[type];
  switch (type) {
    case FilterTypes.Select:
    default:
      return operatorTypes as OperatorTypes[];
  }
}

export function getRelatedFieldsInfo(
  view: IFormedView,
  type: FilterTypes,
  interactionType: InteractionType,
  fields: IControlRelatedField | IControlRelatedField[] | any,
): {
  model: IViewModelProps[],
  fields: IControlRelatedField | IControlRelatedField[]  | any
} {
  const model = Object.entries(view.model)
    .filter(([k, v]: any) => {
      return v.modelType === ViewModelTypes.Category;
    })
    .map(([k, v]: any) => ({
      name: k,
      ...v,
    }));

  if (interactionType === 'column') {
    if (!fields) {
      fields = model.length
        ? {
          name: model[0].name,
          type: model[0].sqlType,
        }
        : undefined;
    }
  } else if (!fields) {
      fields = IS_RANGE_TYPE[type] ? [] :undefined;
    } else {
      fields = IS_RANGE_TYPE[type]
        ? [].concat(fields)
        : fields;
    }

  return {
    model,
    fields,
  };
}

export function getFormedView(view: ISheetItem): IFormedView {
  const { model } = view;
  const formedView = {
    ...view,
    model: JSON.parse((model || '{}')),
  };
  return formedView;
}
